import { director, instantiate, Node, resources } from "cc";
import { DialogViewID } from "../components/DialogViewID";
import { GlobalEventsMgr, GlobalEventsType } from "./GlobelEventMgr";
import { GlobelMgr, Layer } from "./GlobelMgr";
import { DialogViewBase } from "../view/base/DialogViewBase";
import { LogMgr } from "../components/LogMgr";


export class DialogViewManager {
    private static _instance: DialogViewManager;
    private _dialogDataMap:Map<DialogViewID, DialogData> = new Map();
    private _openDialogMap:Map<DialogViewID,DialogViewBase> = new Map();//已经打开的窗口
    private _loadIngs:Map<DialogViewID,DialogViewID> = new Map();//加载中的窗口
    public init():void{
        this.initRegister();
    }
    public static get instance(): DialogViewManager {
        if (!this._instance) {
            this._instance = new DialogViewManager();
        }
        return this._instance;
    }
    private initRegister():void{
        this.registerDialog(DialogViewID.bag,"prefab/dialogPrefab/bag/BagDialogView",Layer.UI_middle);
        this.registerDialog(DialogViewID.rank,"prefab/dialogPrefab/rank/RankDialogView",Layer.UI_middle);
        this.registerDialog(DialogViewID.user,"prefab/dialogPrefab/user/UserDialogView",Layer.UI_middle);
        this.registerDialog(DialogViewID.user,"prefab/dialogPrefab/user/UserDialogView",Layer.UI_middle);
    }
    public registerDialog(ID:DialogViewID, prefabPath: string, layer: Layer=Layer.UI_middle, type: DialogType = DialogType.multiple): void {
        this._dialogDataMap.set(ID,{ ID, prefabPath, type, layer }) ;
    }
    /**获取已打开的窗口 如果未打开则返回null*/
    public getDialog(ID:DialogViewID):DialogViewBase{
        if(this._openDialogMap.has(ID))
        {
            return this._openDialogMap.get(ID);
        }
        return null;
    }
    /**
     * 
     * @param ID 
     * @param data  要传的自定义数据
     * @param parent 指定父类 如果不指定则会被添加到窗口注册数据的那个层
     * @returns 
     */
    public openDialog(ID:DialogViewID, data?:any, parent?: any): void {
        LogMgr.log("打开窗口>>"+ID);
        const dialogData = this._dialogDataMap.get(ID);
        if(this._openDialogMap.has(ID))
        {
            LogMgr.log("窗口已打开");
            this._openDialogMap.get(ID).setData(data);
            return
        }
        if(this._loadIngs.has(ID))
        {
            LogMgr.log("窗口加载中");
            return;
        }
        if (!dialogData) {
            console.error(`Dialog with ID ${ID} is not registered.`);
            return;
        }
        this._loadIngs.set(ID,ID)
        resources.load(dialogData.prefabPath, (err, prefab) => {
            if(!this._loadIngs.has(ID))
            {
                return;
            }
            this._loadIngs.delete(ID);
            if (err) {
                console.error(`预制体加载失败: ${dialogData.prefabPath}`, err);
                return;
            }
            const dialogNode:any = instantiate(prefab);
            const dialogViewBase:DialogViewBase = dialogNode.getComponent(DialogViewBase);
            if (dialogViewBase) {
                dialogViewBase.inspectID(ID);
            } else {
                console.error(`Dialog prefab ${dialogData.prefabPath} does not have DialogViewBase component.`);
                return;
            }
            if(parent)
            {
                dialogNode.parent = parent;
            }else{
                const layerNode = GlobelMgr.instance.getLayer(dialogData.layer);
                dialogNode.parent = layerNode;
            }
            dialogViewBase.setData(data);
            dialogViewBase.show();
            if (dialogData.type === DialogType.only) {
                let  id:DialogViewID;
                this._openDialogMap.forEach((v,k)=>{
                    const dialogData:DialogData = this._dialogDataMap.get(v.getDialogViewID())
                    if(dialogData.type==DialogType.only)
                    {
                        id = v.getDialogViewID();
                    }
                })
                if(id)
                {
                    this.closeDialog(id)
                }
            }
            // 记录已打开的对话框实例
            this._openDialogMap.set(ID,dialogViewBase);
            GlobalEventsMgr.instance.emit(GlobalEventsType.dialogViewOpen,ID);
        });
    }

    public closeDialog(ID:DialogViewID): void {
        LogMgr.log("关闭窗口>>"+ID);
        const dialogNode = this._openDialogMap.get(ID);
        if (dialogNode) {
            dialogNode.node.destroy();
            this._openDialogMap.delete(ID);
            GlobalEventsMgr.instance.emit(GlobalEventsType.dialogViewClose,ID);
        } else if(this._loadIngs.has(ID)){
            this._loadIngs.delete(ID)
        }else{
            console.warn(`Dialog with ID ${ID} is not currently open.`);
        }
    }
}
export enum DialogType {
    only = "only",       // 只允许同时打开一个实例:场景里只会有一个only类型的窗口
    multiple = "multiple",    // 允许同时打开多个实例:场景里可以有多个multiple类型的窗口 但DialogViewID不同 
}
interface DialogData {
    ID: DialogViewID;
    prefabPath: string;
    type: DialogType;
    layer: Layer;
}

